package com.yeyaomai.dksns.flowis.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yeyaomai.dksns.flowis.domain.EngineKeyword;
import com.yeyaomai.dksns.flowis.domain.Keyword;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisQueryOrder;
import com.yeyaomai.dksns.flowis.service.KeywordService;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

@Controller
@RequestMapping("/source/*")
public class KeywordController {

	@Autowired
	private KeywordService keywordService;

	@RequestMapping(method = RequestMethod.GET, value = "/search-word")
	public String keywordEngine(HttpServletRequest request,
			HttpServletResponse httpResponse, FlowisQueryOrder order,
			ModelMap modelMap) {

		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));

		
		Page<Keyword> kwPage  = keywordService.getSplit(order);
		
		if(kwPage.getContent() != null) {
			
			List<EngineKeyword> engineKeywords = new ArrayList<EngineKeyword>(); 
			for (Keyword keyword : kwPage.getContent()) {
				
				engineKeywords = keywordService.queryEngineKeywordByDate(keyword.getKeyword(), order.getStartTime(), order.getEndTime());
				keyword.setEngineKeywords(engineKeywords);
			}
		}
		
		
		modelMap.addAttribute("kwPage", kwPage);
		modelMap.addAttribute("order", order);

		return "search-word";

	}

}
